﻿using lingopen.Exceptions;
using lingopen.IdStrategy;
using lingopen.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Chloe;
using lingopen.AutoMapper;
using lingopen.Entity.CRM;
using System.Net;
using Newtonsoft.Json.Linq;
using lingopen.Application.CRM.Models.WorkBill;

namespace lingopen.Application.CRM.Implements
{
    public class CustomerAppService : AdminAppService, ICustomersAppService
    {
        public CRM_WorkBill GetWorkBillByCode(int wb)
        {
            return DbContext.Query<CRM_WorkBill>(p => p.Code == wb).FirstOrDefault();
        }
        public CRM_Customer GetCustomer(string custCode)
        {
            var q = this.DbContext.Query<CRM_Customer>().FilterDeleted().Where(p => p.Code == custCode);
            return q.FirstOrDefault();
        }
        public PagedData<WorkBillModel> GetWorkBill(Pagination pagination, string cust_id, string keyword)
        {
            var q = this.DbContext.JoinQuery<CRM_WorkBill, CRM_Customer, CRM_Customer_WxUser, CRM_Customer_WxUser>((a, b, c, d) => new object[] {
                    JoinType.InnerJoin,a.CustomerID==b.Id,
                    JoinType.InnerJoin,a.CustomerOpenID==c.WxOpenID,
                    JoinType.InnerJoin,a.StaffOpenID==d.WxOpenID&&d.IsStaff==true&&d.CustomerID==a.CustomerID });
            if (!string.IsNullOrEmpty(cust_id))
            {
                q = q.Where((a, b, c, d) => a.CustomerID == cust_id);
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                q = q.Where((a, b, c, d) => c.RealName.Contains(keyword) || c.NickName.Contains(keyword) || c.PhoneNum.Contains(keyword)
                || d.RealName.Contains(keyword) || d.NickName.Contains(keyword) || d.PhoneNum.Contains(keyword)
                || b.Name.Contains(keyword) || b.Code.Contains(keyword)
                || a.Name.Contains(keyword));
            }
            var select = q.Select((a, b, c, d) => new WorkBillModel
            {
                Id = a.Id,
                Code = a.Code,
                Name = a.Name,
                CustomerID = a.CustomerID,
                CustomerName = b.Name,
                CustomerOpenID = a.CustomerOpenID,
                CustomerRealName = c.RealName,
                Description = a.Description,
                StaffOpenID = a.StaffOpenID,
                StaffRealName = d.RealName,
                StartTime = a.StartTime,
                Status = string.IsNullOrEmpty(a.Status) ? "未受理"
                         : (a.Status == "start" ? "未受理"
                         : (a.Status == "running" ? "处理中" : (a.Status == "close" ? "已关闭" : (a.Status == "send" ? "已转发" : "未受理")))),
                StopTime = a.StopTime
            });
            select = select.OrderByDesc(p => p.Code);
            PagedData<WorkBillModel> ret = select.TakePageData(pagination);
            return ret;
        }

        public PagedData<CRM_Customer_WxUser> GetWxStaff(Pagination pagination, string cust_id, string keyword)
        {
            var q = this.DbContext.Query<CRM_Customer_WxUser>().FilterDeleted().Where(p => p.IsStaff == true);
            q = q.WhereIfNotNullOrEmpty(cust_id, a => a.PMSID == cust_id);
            q = q.WhereIfNotNullOrEmpty(keyword, a => a.WxOpenID == keyword || a.RealName.Contains(keyword) || a.NickName.Contains(keyword) || a.PhoneNum.Contains(keyword));
            q = q.OrderByDesc(a => a.CreationTime);
            PagedData<CRM_Customer_WxUser> ret = q.TakePageData(pagination);
            return ret;
        }
        public PagedData<CRM_Customer> GetCustomersList(Pagination pagination, string keyword)
        {
            var q = this.DbContext.Query<CRM_Customer>().FilterDeleted().WhereIfNotNullOrEmpty(keyword, a => a.Code == keyword || a.Name.Contains(keyword) || a.Description.Contains(keyword));
            q = q.OrderBy(a => a.Code);
            PagedData<CRM_Customer> ret = q.TakePageData(pagination);
            return ret;
        }
        public PagedData<CRM_PMS> GetPMSsList(Pagination pagination, string keyword)
        {
            var q = this.DbContext.Query<CRM_PMS>().FilterDeleted().WhereIfNotNullOrEmpty(keyword, a => a.Code == keyword || a.Name.Contains(keyword) || a.Description.Contains(keyword));
            q = q.OrderBy(a => a.Code);
            PagedData<CRM_PMS> ret = q.TakePageData(pagination);
            return ret;
        }
        public void Add(AddCustomerInput input)
        {
            input.Validate();
            this.DbContext.InsertFromDto<CRM_Customer, AddCustomerInput>(input);
        }

        public void Update(UpdateCustomerInput input)
        {
            input.Validate();
            this.DbContext.UpdateFromDto<CRM_Customer, UpdateCustomerInput>(input);
        }

        public void DeleteById(string id)
        {
            id.NotNullOrEmpty();
            this.DbContext.DeleteByKey<CRM_Customer>(id);
        }

        public List<SimpleCustomerModel> GetCustomerSimpleModels()
        {
            var q = this.DbContext.Query<CRM_Customer>().FilterDeletedAndDisabled().OrderBy(a => a.Name);
            var ret = q.Select(a => new SimpleCustomerModel() { Id = a.Id, Name = a.Name }).ToList();
            return ret;
        }
        public List<SimplePMSModel> GetPMSsSimpleModels()
        {
            var q = this.DbContext.Query<CRM_PMS>().FilterDeletedAndDisabled().OrderBy(a => a.Name);
            var ret = q.Select(a => new SimplePMSModel() { Id = a.Id, Name = a.Name }).ToList();
            return ret;
        }

        ///// <summary>
        ///// 新增工作人员和酒店的关联CRM_Customer_WxStaff
        ///// </summary>
        ///// <param name="openId"></param>
        ///// <param name="customerCode"></param>
        ///// <returns></returns>
        //public bool AddCRMStaff(string openId, string customerCode)
        //{
        //    if (string.IsNullOrEmpty(openId)) return false;
        //    if (string.IsNullOrEmpty(customerCode)) return false;
        //    try
        //    {
        //        this.DbContext.DoWithTransaction(() =>
        //        { 
        //            CRM_Customer_WxStaff insert = CreateEntity<CRM_Customer_WxStaff>();
        //            insert.CustomerCode = customerCode;
        //            insert.WxOpenID = openId;
        //            DbContext.Insert(insert);
        //        });
        //    }
        //    catch (Exception)
        //    {
        //        return false;
        //    }
        //    return true;
        //}
        ///// <summary>
        ///// 取消工作人员和酒店的服务关联
        ///// </summary>
        ///// <param name="openId"></param>
        ///// <param name="customerCode"></param>
        ///// <returns></returns>
        //public bool DeleteCRMStaff(string openId, string customerCode)
        //{
        //    if (string.IsNullOrEmpty(openId)) return false;
        //    if (string.IsNullOrEmpty(customerCode)) return false;
        //    try
        //    {
        //        this.DbContext.DoWithTransaction(() =>
        //        {
        //            DbContext.Delete<CRM_Customer_WxStaff>(a => a.WxOpenID == openId && a.CustomerCode == customerCode);
        //        });
        //    }
        //    catch (Exception)
        //    {
        //        return false;
        //    }
        //    return true;
        //}

    }
}
